<?php

namespace App\Admin\Actions\Post;

use App\Model\CoinLog;
use App\Model\Message;
use App\Model\User;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use App\Model\Withdraw;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UpdateWithdrawFail extends BatchAction
{
    public $name = "<a class='report-posts-fail btn btn-sm btn-info'><i class='fa fa-info-circle'></i>不允许提现</a>";
    protected $selector = '.report-posts-fail';

    public function handle(Collection $collection, Request $request)
    {
        $ids = $request->input('_key');

        $ids = is_array($ids) ? $ids :  explode(',', $ids);
        if(count($ids)<=0){
            return $this->response()->error('请选择要操作的ID')->refresh();
        }
        if(count($ids)>20){
            return $this->response()->error('一次最多只能选择20个哦！')->refresh();
        }

        $ret = ['ret' => 0, 'message' => '操作成功！'];
        foreach ($ids as $key => $val){
            $id = $val;
            DB::beginTransaction();
            try {
                $record = Withdraw::find($id);
                //记录不存在
                if (!$record) {
                    continue;
                }

                //状态不等于审核状态不给与操作
                if ($record->status != Withdraw::STATUS_ING) {
                    continue;
                }

                //判断用户状态
                $userInfo = User::find($record->user_id);
                if(empty($userInfo) || $userInfo->status != 0 ){
                    continue;
                }

                if ($record->out_trans_id) {
                    continue;
                }
                //修改状态
                Withdraw::where('id', $id)->limit(1)->update(['status' => Withdraw::STATUS_FAIL]);
                $userCoin = UserCoin::gainIncome($record->user_id, $record->withdraw_coin);
                CoinLog::addIncome($record->user_id, $record->withdraw_coin, CoinLog::FROM_WITHDRAW_BACK, $userCoin);
                //不允许提现申请
                Message::pushSystem($record->user_id, '你的提现申请暂不通过！如有疑问，请联系在线客服', '提现通知');
                DB::commit();
                // else DB::rollBack();
            } catch (Exception $e) {
                DB::rollBack();
                Log::info(__CLASS__ . "==WithdrawId:{$id}==Exception:" . $e->getMessage());
//                return ['ret' => -1, 'message' => '提现提交异常！'];
            }
        }
        return $this->response()->success('修改成功')->refresh();
    }

    public function dialog($ids = '')
    {
        $this->confirm('确认执行该操作么？');
    }

    public function html()
    {
        return "<a class='report-posts-fail btn btn-sm btn-info'><i class='fa fa-info-circle'></i>提现审核</a>";
    }
}
